<template>
  <div class="select-container">
    <el-row :gutter="10">
      <el-col :span="12" class="device-container">
        <div class="label">摄像头</div>
        <el-select
          :disabled="!deviceCanSelect"
          class="select"
          v-model="store.videoDeviceId"
          placeholder="请选择空闲的摄像头"
          @change="handleDeviceChange"
        >
          <el-option
            v-for="item in store.cameraList"
            :key="item.deviceId"
            :label="item.label"
            :value="item.deviceId"
          >
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="12" class="device-container">
        <div class="label">麦克风</div>
        <el-select
          :disabled="!deviceCanSelect"
          class="select"
          v-model="store.audioDeviceId"
          placeholder="请选择麦克风"
          @change="handleDeviceChange"
        >
          <el-option
            v-for="item in store.microphoneList"
            :key="item.deviceId"
            :label="item.label"
            :value="item.deviceId"
          >
          </el-option>
        </el-select>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { onMounted } from 'vue';
import TRTC from 'trtc-js-sdk';
import { ElMessage } from 'element-plus/es';
import appStore from '@/store/index';
import type { DeviceItem } from '@/types/type';

const store = appStore();
const emit = defineEmits(['switchDevice']);

// 控制设备是否可选
defineProps<{
  deviceCanSelect: boolean;
}>();

const updateDevice = async () => {
  console.log('updateDevice');
  const cameraItems: DeviceItem[] = await TRTC.getCameras();
  cameraItems.forEach((item) => {
    item.value = item.deviceId;
  });
  const microphoneItems: DeviceItem[] = await TRTC.getMicrophones();
  microphoneItems.forEach((item) => {
    item.value = item.deviceId;
  });

  store.$patch({
    cameraList: cameraItems,
    microphoneList: microphoneItems,
  });


};

navigator.mediaDevices
  .getUserMedia({ audio: true, video: true })
  .then((stream) => {
    stream.getTracks().forEach((track) => {
      track.stop();
    });
    updateDevice();
  })
  .catch(() => {
    ElMessage({ message: '获取音视频信息失败', type: 'error' });
  });

onMounted(() => {
  updateDevice();
});

navigator.mediaDevices.ondevicechange = updateDevice;

const handleDeviceChange = () => {
  emit('switchDevice', {
    videoId: store.videoDeviceId,
    audioId: store.audioDeviceId,
  });
};
</script>

<style lang="scss" scoped>
.select-container {
  padding-bottom: 5px;

  .device-container {
    display: flex;
    width: 100%;
  }

  .label {
    padding: 0 20px;
    width: 120px;
    height: 32px;
    line-height: 32px;
    font-size: 14px;
    border-top: 1px solid #dcdfe6;
    border-left: 1px solid #dcdfe6;
    border-bottom: 1px solid #dcdfe6;
    border-radius: 4px 0 0 4px;
    color: #212529;
    background-color: #f5f7fa;
  }

  .select {
    width: 100%;
  }
}
</style>
